package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.CWeightSheets;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysLog;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysLog;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysLoginlog;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.LogExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.LogExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysLogService;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.ISysLoginlogService;
import com.xiaoxu.intranetweb.util.SzResult;
import lombok.ToString;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;

/**
 * syslog业务层
 * @author xiaoxu
 * @date 2023/2/07 15:00
 * @version 1.0
 * @since 1.0
 */
@Component
public class SysLogBu {
    @Autowired
    private ISysLogService sysLogService;
    @Autowired
    private ISysLoginlogService sysLoginLogService;
//    日志记录

    /**
     * 日志记录
     * @param type 日志类型
     * @param name 日志名称
     * @param detail 日志详情
     */
    public void logRecord(String type, String name, String detail,String dataFrom){
//    往SysLog表中插入数据
        String uuid = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
        SysLog sysLog = new SysLog();
        sysLog.setId(uuid);
        sysLog.setLogType(type);
        sysLog.setLogName(name);
        sysLog.setLogDetail(detail);
        sysLog.setLogSource(1);
        sysLog.setLogTime(LocalDateTime.now());
        if (dataFrom != null && !dataFrom.isEmpty()){
            sysLog.setDataFrom(dataFrom);
        }
        sysLogService.save(sysLog);
    }
//    查询日志
    public SzResult logQuery(String page, String pageSize,String startTime, String endTime, String value,String plantId){
//        分页
        Page<SysLog> page1 = new Page<>(Integer.parseInt(page),Integer.parseInt(pageSize));
//        模糊查询
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();
        if ( value != null && !value.equals("")) {
            queryWrapper.and(wrapper -> wrapper.like("LOG_TYPE", value)
                    .or().like("LOG_NAME", value).or().like("LOG_DETAIL",value));
        }
        queryWrapper.between(startTime !=null && !startTime.equals("") && endTime !=null && !endTime.equals("") ,"LOG_TIME", startTime, endTime);
        queryWrapper.orderByDesc("LOG_TIME");
        queryWrapper.eq("DATA_FROM",plantId);
        IPage<SysLog> iPage = sysLogService.page(page1,queryWrapper);
        List<SysLog> logsList = iPage.getRecords();
        Long total = iPage.getTotal();
        Map<String,Object> map = new HashMap();
        map.put("total",total);
        map.put("items",logsList);
        return  SzResult.success(map);
    }

    public Future<List<LogExcelEn>> exportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String plantId, String logType, String logName, String startTime, String endTime) {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<LogExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        LogExcelEn logExcelEn = LogExcelEn.builder().build();

                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("logType")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogType(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("logName")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("logDetail")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogDetail(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("logTime")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogTime(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(logExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like(logType != null && !logType.equals(""), "LOG_TYPE", logType);
                    queryWrapper.like(logName != null && !logName.equals(""), "LOG_NAME", logName);
                    queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "LOG_TIME", startTime, endTime);
                    List<SysLog> sysLogs = sysLogService.list(queryWrapper);
                    for (SysLog sysLog : sysLogs) {
                        LogExcelEn logExcelEn = LogExcelEn.builder()
                                .logType(Optional.ofNullable(sysLog.getLogType()).orElse(""))
                                .logName(Optional.ofNullable(sysLog.getLogName()).orElse(""))
                                .logDetail(Optional.ofNullable(sysLog.getLogDetail()).map(Object::toString).orElse(""))
                                .logTime(Optional.ofNullable(sysLog.getLogTime()).map(Object::toString).orElse(""))
                                .build();
                        list.add(logExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        LogExcelEn logExcelEn = LogExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("logType")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogType(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("logName")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogName(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("logDetail")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogDetail(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("logTime")) {
                                if (entry.getValue() != null) {
                                    logExcelEn.setLogTime(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(logExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }



    public void loginRecord(String id, String ip){
//    往SysLog表中插入数据
        String uuid = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
        SysLoginlog sysLoginLog = new SysLoginlog();
        sysLoginLog.setId(uuid);
        sysLoginLog.setUserId(id);
        sysLoginLog.setLoginTime(LocalDateTime.now());
        sysLoginLog.setLoginIp(ip);
        sysLoginLog.setLoginType("1");
        sysLoginLogService.save(sysLoginLog);
    }
}
